package com.qsmx.core.util;

import android.annotation.SuppressLint;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.regex.Pattern;

public class StringUtil {

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static boolean isNotEmpty(String s) {
        return !isEmpty(s);

    }

    public static boolean isNull(String str) {
        return str == null;
    }

    public static boolean isNotNull(String str) {
        return str != null;
    }

    public static String changeBooleanToString(boolean b) {
        if (b) {
            return "true";
        } else {
            return "false";
        }
    }

    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotBlank(String s) {
        return !StringUtil.isBlank(s);
    }

    @SuppressLint("SimpleDateFormat")
    public static String getDateByTimestamp(long timeStampLong) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date netDate = new Date(timeStampLong);
        return sdf.format(netDate);
    }

    @SuppressLint("SimpleDateFormat")
    public static String getDateByTimestampLong(long timeStampLong) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date netDate = new Date(timeStampLong);
        return sdf.format(netDate);
    }

    @SuppressLint("SimpleDateFormat")
    public static String getHourByTimestampLong(long timeStampLong) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        Date netDate = new Date(timeStampLong);
        return sdf.format(netDate);
    }

    @SuppressLint("SimpleDateFormat")
    public static String getDateByTimestampHasNoHour(long timeStampLong) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00.000 Z");
        Date netDate = new Date(timeStampLong);
        return sdf.format(netDate);
    }

    /* 时间戳转换成字符窜 */
    public static String getDateTimeToStringHasNoHour(Date d) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        return sf.format(d);
    }

    /* 将字符串转为时间戳 时分秒 */
    public static long getStringToDateTime(String time) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//注意格式化的表达式
        Date date = new Date();
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date.getTime();
    }

    public static String[] getThisMonthStartAndEndTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String[] startAndEndDate = new String[2];//定义数组用于存放起始时间[0]和结束时间[1]
        //获取当月前的月的起始时间和结束时间
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1, 0, 0, 0);//设置当月的起始时间
        startAndEndDate[0] = formatter.format(calendar.getTime());//存放到数组中
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(
                Calendar.DAY_OF_MONTH));//设置当月结束天为当月的最大天，如：9月份最大天为30，此时设置天为30
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DATE), 23, 59, 59);//设置当月的结束时间
        startAndEndDate[1] = formatter.format(calendar.getTime());//存放到数组中
        return startAndEndDate;
    }

    /* 将字符串转为时间戳 时分秒 */
    public static long getStringToDateTimes(String time) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss 'Z'");//注意格式化的表达式
        Date date = new Date();
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date.getTime();
    }

    /* 将字符串转为时间戳 时分秒 */
    public static long getStringToDateTimeNoT(String time) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");//注意格式化的表达式
        Date date = new Date();
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date.getTime();
    }

    /* 将字符串转为时间戳 时分秒 */
    public static long getStringToDateTimeNoTime(String time) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");//注意格式化的表达式
        Date date = new Date();
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date.getTime();
    }

    /**
     * 时间戳转换成日期字符窜
     */
    public static String getDateToStringToday(long time) {
        Date d = new Date(time);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
        return sf.format(d);
    }

    public static String getLongTimeToStringTime(long lastTime) {

        long nowTime = lastTime;
        long hour = 0;
        long min = 0;
        String lastTimeStr;

        if (nowTime >= 60 && nowTime < 120) {
            hour = hour + 1;
            min = nowTime - 60;
        } else if (nowTime >= 120 && nowTime < 180) {
            hour = hour + 2;
            min = nowTime - 120;
        } else if (nowTime >= 180 && nowTime < 240) {
            hour = hour + 3;
            min = nowTime - 180;
        } else if (nowTime >= 240 && nowTime < 300) {
            hour = hour + 4;
            min = nowTime - 240;
        } else {
            min = nowTime;
        }

        if (hour > 0 && min <= 0) {
            lastTimeStr = "还剩" + hour + "小时";
        } else if (hour > 0 && min > 0) {
            lastTimeStr = "还剩" + hour + "小时" + min + "分钟";
        } else if (hour <= 0 && min > 0) {
            lastTimeStr = "还剩" + min + "分钟";
        } else {
            lastTimeStr = "";
        }

        return lastTimeStr;
    }


    /**
     * 时间戳转换成日期字符窜
     */
    public static String getDateToStringTodayHasHour(long time) {
        Date d = new Date(time);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return sf.format(d);
    }

    public static boolean isValidEMail(String eMail) {
        String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        return Pattern.matches(regex, eMail);
    }

    /**
     * 四舍五入保留一位小数
     *
     * @param f
     * @return
     */
    public static String getDecimalFormat(float f) {
        String parten = "#.#";
        DecimalFormat decimal = new DecimalFormat(parten);
        String str = decimal.format(f);
        // System.out.println(">>>>>>>>>>>> " + f + "   " + str);
        return str;
    }

    public static String getRegex(String token) {
        String str = token;
        str = str.replaceAll("\\+", "%2B").replaceAll("\"", "%22").replaceAll("'", "%27").replaceAll("\\/", "%2F");
        return str;
    }

    public static String getNotNullString(String string) {
        if (string == null) {
            return "";
        }
        return string;

    }

    public static String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
//
//    private static List<Cookie> cookies;
//
//    public static List<Cookie> getCookies() {
//        return cookies != null ? cookies : new ArrayList<Cookie>();
//    }
//
//    public static void setCookies(List<Cookie> cookies) {
//        StringUtil.cookies = cookies;
//    }

    /**
     * Integer valueof
     */
    public static int IntegerValueOf(String valueStr, int defaultI) {
        if (valueStr == null || valueStr.length() == 0)
            return defaultI;
        int result = 0;
        try {
            result = Integer.valueOf(valueStr);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }

    /**
     * Double valueof
     */
    public static double DoubleValueOf(String valueStr, double defaultD) {
        if (valueStr == null || valueStr.length() == 0)
            return defaultD;
        double result = defaultD;
        try {
            result = Double.valueOf(valueStr);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }

    /**
     * Long valueof
     */
    public static long LongValueOf(String valueStr, long defaultL) {
        if (valueStr == null || valueStr.length() == 0)
            return defaultL;
        long result = defaultL;
        try {
            result = Long.valueOf(valueStr);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }


    /* 时间戳转换成字符窜 */
    public static String getDateTimeToString(Date d) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        return sf.format(d);
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][0-9][0-9]\\d{8}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (StringUtil.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

    public static String getDistance(String distance) {

        Double dis = Double.valueOf(distance);
        String back = "";
        if (dis > 1000) {
            back = dis / 1000 + "km";
        } else {
            back = dis + "m";
        }
        return back;

    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 获取随机字符串
     */
    public static String getRandomString(int length) {
        //length表示生成字符串的长度
        String str = "abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }


    /**
     * 获取随机字符串
     */
    public static String getRandomNumString(int length) {
        //length表示生成字符串的长度
        String str = "1234567890";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 必须是6到20位数字和字母组合
     *
     * @param txt
     * @return
     */
    public static boolean isDigtalLetter(String txt) {
        if (txt.length() >= 6) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 必须是6到20位数字或字母
     *
     * @param txt
     * @return
     */
    public static boolean isDigtalOrLetter(String txt) {
        Pattern p = Pattern.compile("(?![0-9]+$)|(?![a-zA-Z]+$)|[0-9A-Za-z]{6,20}");
        return p.matcher(txt).matches();
    }

    public static String asciiStringToHex(String asciiString) {
        StringBuilder hexStringBuilder = new StringBuilder();
        for (char c : asciiString.toCharArray()) {
            hexStringBuilder.append(String.format("%02X", (int) c));
        }
        return hexStringBuilder.toString();
    }

    public static String hexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String substring = hex.substring(i, i + 2);
            int ch = Integer.parseInt(substring, 16);
            sb.append((char) ch);
        }
        return sb.toString();
    }

    /**
     * 手机号用****号隐藏中间数字
     *
     * @param phone
     * @return
     */
    public static String getPhoneNum(String phone) {
        String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phone_s;
    }
}
